<?
/**
 *订单记录类.
 *查询订单详情和处理订单的相关操作.
 */
class OrderRecord{
    /**
     *订单号.
     *var int 
     */
    protected $ordernum;
    
    /**
     *票付通内部接口对象
     *@var object
     */
    protected $s;
    
    /**
     *键值数组对应UUstatus文本和样式
     *@static
     *@var array 
     */
    public static $UUstatusT=array(0=>"未使用",1=>"<em class='green'>已使用</em>",2=>"已过期",3=>"<em class='red'>已取消</em>",4=>"被替代",5=>"被修改",6=>"已撤销",7=>"部分使用");
    
    /**
     *键值数组对应UUstatus文本和样式
     *@static
     *@var array 
     */
    public static $statusT=array("0"=>"未使用","1"=>"<em class='green'>已使用</em>","2"=>"<em class='gray'>已过期</em>","3"=>"<em class='red'>已取消</em>","4"=>"凭证码被替代","6"=>"被终端撤销</br><em class='red'>(已取消)</em>","5"=>"被终端修改</br><em class='green'>(已使用)</em>");

    public static $_nSStatusT=array("0"=>"未使用","1"=>"已使用","2"=>"已过期","3"=>"已取消","4"=>"凭证码被替代","6"=>"被终端撤销</br>(已取消)","5"=>"被终端修改----(已使用)");

    /**
     *键值数组对应UUpmode文本和样式
     *@static
     *@var array 
     */
    public static $paymodeT=array(
        0=>"账户余额",
        1=>"支付宝",
        2=>"授信支付",
        3=>"产品自销",
        4=>"现场支付",
        5=>"微信支付",
        6=>'会员卡支付',
        7=>'银联支付',//这个位置已经被我承包了 zax
        8=>'环迅支付'
    );
    
    /**
     *键值数组对应UUpaystatus文本和样式
     *@static
     *@var array 
     */
    public static $paystatusT=array(1=>"<em class='green'>(已支付)</em>",2=>"<em class='orange'>(待支付)</em>");
    
    /**
     *键值数组对应门票产品类型
     *@static
     *@var array 
     */
    public static $p_typeT=array("A"=>"门票","B"=>"线路","C"=>"酒店","D"=>"商品","F"=>"套票");
    
    /**
     *构造函数.
     *@param int $ordernum 订单号
     *@param object 票付通内部接口对象
     */
    public function __construct($ordernum, $s){
        $this->ordernum=$ordernum;
        $this->s=$s;
    }
    
    /**
     *格式化订单记录函数.
     *联票订单将以存在主订单和从订单，非联票订单制存在主订单
     *@param object simplexml对象
     *@return array
     */
    public static function format($simxml){
        $info=array();
        $info['childOrder']=array();
        $info['orderAlipay']=false;
        $info['orderCancel']=false;
        $info['orderAlter'] =false;
        $count=count($simxml);

        $child_ordernum_arr = array();
        foreach($simxml as $row){
            if($child_ordernum_arr[(int)$row->UUordernum]) continue;
            $child_ordernum_arr[(int)$row->UUordernum] = 1;
            if($count>1){
                if((int)$row->UUconcat_id===(int)$row->UUordernum){
                    $info['mainOrder'] = $row;
                }else{
                    $info['childOrder'][]=$row;
                }
            }
            else{
                $info['mainOrder']=$row;
            }
            $info['totalPrice'] +=(int)$row->UUtotalmoney;
            $info['totalTnum']  +=(int)$row->UUtnum;
            $info['totalOrder']++;

        }
        $paystatus = (int)$info['mainOrder']->UUpaystatus;
        $status = (int)$info['mainOrder']->UUstatus;
        $buyid = (int)$info['mainOrder']->UUbuyid;
        $mid = (int)$info['mainOrder']->UUmid;
        $pmode = (int)$info['mainOrder']->UUpmode;
        $contacttel = (int)$info['mainOrder']->UUcontacttel;
        if((string)$info['mainOrder']->UUaids!='0'){
            $aid_ori = explode(',',(string)$info['mainOrder']->UUaids);
            $aid_ori = $aid_ori[0];
        }else
            $aid_ori = (int)$info['mainOrder']->UUaid;
        // 购买人支付未支付订单（支付宝订单）
        if($pmode==1 && $paystatus!=1 && $status==0 && $buyid==$_SESSION['sid']){
            $info['orderAlipay']=true;
        }
        // 散客未支付可取消
        if($contacttel == $_SESSION['account'] && $status==0) $info['orderCancel']=true;
        
        // 散客支付完有修改权限
        if($contacttel == $_SESSION['account'] && $paystatus==1 && $status==0){
            $info['orderAlter']=true;
        }
        // 平台订单并且已支付
        // if($info['mainOrder']->UUremotenum==0 && $paystatus==1){
		// 分销商已支付的订单
        if($paystatus==1){
            // 购买人有修改和重发权限()
            // $fit = in_array((int)$info['mainOrder']->UUordermode,array(1,2));
            $fit = (int)$info['mainOrder']->UUordermode;//  0.分销商
            $fit = !(!$fit || $fit == 9);

            if($status==0 && $mid==$_SESSION['sid'] && !$fit){
                $info['orderAlter']=true;
                $info['orderResend']=true;
                $info['orderCancel']=true;
            }
   
            // 已过期可取消，过期做了权限判断 20151026 TongBaoChun
            if($status==2 && ($_SESSION['sid'] == 1 || $buyid==$_SESSION['sid']) && !$fit){
                $info['orderCancel']=true;
            }

            //已支付未使用 最初的供应商可以重发

            if($status==0 && $aid_ori==$_SESSION['sid'] && !$fit){
                $info['orderResend']=true;
            }

			
			// 已过期最下级卖家可以取消
//			if($status==2 && $aid==$_SESSION['sid'] && !$fit){
//				$info['orderCancel']=true;
//			}

        }

		// 平台订单可以取消
		if((string)$info['mainOrder']->UUordername=='淘宝码商' && $paystatus==1){
			$fit = in_array((int)$info['mainOrder']->UUordermode,array(1,2));
            if($status==0 && $buyid==$_SESSION['sid'] && !$fit){
                $info['orderCancel']=true;
            }
		}

        // 未支付并且是购买者给取消权限
        if($paystatus==2 && $status==0 && $buyid==$_SESSION['sid']){
            $info['orderCancel']=true;
        }
        
        // 现场支付（包含自销）
        if( ($pmode==4 || $pmode==3) && $status==0){
            $info['orderCancel']=1;
            $info['orderResend']=1;
        }
        if( ($pmode==4 || $pmode==3) && $mid==$_SESSION['sid'] && $status==0) $info['orderAlter'] =1;

        return $info;
    }
    /*订单操作（查看，修改，重发，取消,支付）权限*/
    /**
     *格式化订单记录函数.
     *联票订单将以存在主订单和从订单，非联票订单制存在主订单
     *@param object simplexml对象
     *@return array
     *说明：童改写，解决订单号查询时没有从订单。不改变源码做冗余；
     */
    public static function _format($simxml,$other){
        $info=array();
        $info['childOrder']=array();
        $info['orderAlipay']=false;
        $info['orderCancel']=false;
        $info['orderAlter']=false;
        $count=count($simxml);

        // echo $count;
        // print_r($other);
        // exit;
        foreach($simxml as $row){
            if($count>1){
                if($row->UUifpack>0){
                    if($row->UUifpack==1){
                        $info['mainOrder']=$row;
                    }else{
                        $info['packOrder'][]=$row;
                        continue;
                    }
                }else{
                    if($row->UUconcat_id=="main"){
                        $info['mainOrder']=$row;

                    }else{
                        $info['childOrder'][]=$row;
                    }
                }
            }else{
                // echo "我来也";
                $info['mainOrder']=$row;
                if(count($other)){
                    $info['childOrder'][]=$other;
                }
            }
            $info['totalPrice']+=(string)($row->UUtnum*$row->UUtprice);
            $info['totalTnum']+=(string)$row->UUtnum;
            $info['totalOrder']++;
            if(count($other)){
                $info['totalOrder']+=count($other);
                $info['totalPrice']+=(string)($other->UUtnum*$other->UUtprice);
            }
        }
        if($info['mainOrder']->UUpmode==1&&$info['mainOrder']->UUpaystatus!=1 && $info['mainOrder']->UUstatus==0){
            $info['orderAlipay']=true;
        }

        if($info['mainOrder']->UUremotenum==0 && (int)$info['mainOrder']->UUpaystatus==1){

            if(in_array((int)$info['mainOrder']->UUstatus,array(0))){
                $info['orderAlter']=true;
                $info['orderResend']=true;
            }
            if(in_array((int)$info['mainOrder']->UUstatus,array(0,2))){
                $info['orderCancel']=true;
            }

        }
        //现场支付
        if((int)$info['mainOrder']->UUpmode==4 && (int)$info['mainOrder']->UUstatus==0){
            $info['orderAlter'] =1;
            $info['orderCancel']=1;
            $info['orderResend']=1;
        }

        return $info;
    }

    /**
     *订单操作权限查询函数.
     *查看用户是否有订单操作权限
     *@param int $order 订单号
     *@param int $did 操作人ID
     *@param int $account 普通用户账号，机预订手机号
     *@param string $auth 需查询权限字段 orderView,orderCancel,orderAlter,orderChange
     *@return array
     */
    public static function orderOperAuth($order,$did,$account="",$auth){
        if($auth=="orderView"){
            if($did==(string)$order['mainOrder']->UUmid || $did==(string)$order['mainOrder']->UUaid||$did==1)
            return true;
        }
        if($auth == 'orderAlter' && $order[$auth]){
                if($order['childOrder']){
                    foreach($order['childOrder'] as $cr){
                        if((int)$cr['mainOrder']->UUtnum!=1)
                            goto re;//当订单的数量全部都是1时 不显示修改
                    }
                }
                if((int)$order['mainOrder']->UUtnum != 1)
                    goto re;
            return false;
        }
        re:

        if($auth=="orderAlter" || $auth=="orderCancel" || $auth=='orderResend' ){ // 先行同步的 现场支付的 不让取消和修改
            if((string)$order['mainOrder']->UUpaystatus==0 && strpos('a'.(string)$order['mainOrder']->UUremotenum,'16u_')>0) return false;
        }
		// 先行同步的不让取消和修改
		if($auth=="orderAlter" || $auth=="orderCancel" || $auth=='orderResend' ){
            if((string)$order['mainOrder']->UUsync_status==2 && (string)$order['mainOrder']->UUremotenum!=0) return false;
        }

        if ($auth == 'orderResend' && $order[$auth]) {
            //散客订单可由原始供应商发送短信——Guangpen Chen Add It.
            $idArr = array(
                (int)$order['mainOrder']->UUsellid,
                (int)$order['mainOrder']->UUaid,
                (int)$order['mainOrder']->UUmid
            );

            if(in_array($did , $idArr)) return true;

        }
        else {
            
            if((int)$order['mainOrder']->UUordermode==0 && $order[$auth]){//分销下单权限
                if($did==(int)$order['mainOrder']->UUmid || $did==(int)$order['mainOrder']->UUsellid)
                    return true;
            }
        }

        if((int)$order['mainOrder']->UUordermode==0 && $order[$auth]){//分销下单权限
            if($did==(int)$order['mainOrder']->UUmid || $did==(int)$order['mainOrder']->UUsellid)
                return true;
        }
        
        $fit = in_array((int)$order['mainOrder']->UUordermode,array(1,2,9));
        
        if( $fit && $order[$auth]){// 普通用户下单
            if($account==(string)$order['mainOrder']->UUcontacttel) return true;
                
        }
        
        
        $paystatus = (int)$order['mainOrder']->UUpaystatus;
        $usestatus = (int)$order['mainOrder']->UUstatus;

        //过期只有管理员可以取消
        if ($usestatus==2 && $_SESSION['sid']==1 && $auth == 'orderCancel')return true;

        // 自己购买未支付可取消
        if(($paystatus==2)&&($usestatus==0) && $order[$auth]) return true;

        // 散客已支付可修改
        if(($paystatus==1)&&($usestatus==0) && $order[$auth] && $fit) return true;
        return false;
    }
    //判断订单是否有被验证的权限
    public static function orderChkAuth($row){
        if((string)$row->UUp_type=='F')return false;//套票不显示
        $pay = (int)$row->UUpaystatus=='0'?true : false;//0是现场支付

        if(
            !((int)$row->UUstatus==0 && (int)$row->UUpaystatus==1) &&//已支付未使用
            !($pay==true && (int)$row->UUstatus==0) //现场支付未使用
        )
            return false;
        if($_SESSION['sid']==1) return true;//管理员
        if((string)$row->UUaids!=0){//出售者
            $aid = explode(',',(string)$row->UUaids);
            $aid = $aid[0];
        }else
            $aid = (int)$row->UUaid;

        if($aid==$_SESSION['sid']){
            return true;
        }
    }
    /**
     *查询订单数据.
     *联票也一同被返回,故有可存在对个simplexml对象
     *@return object
     */
    public function info_bk($ifpack=1,$concat_id=0){
        //$ifpack=1;
        $xml=$this->s->Order_Globle_Search("","","","","","","","","","","","",
            $this->ordernum,"","","","","",1,1,0,999,"","","","","","","","","",
            $concat_id,$ifpack);

        $simxml = simplexml_load_string($xml);
        //TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","",
                "","","","","","",$this->ordernum,"","","","","",1,1,0,999,"",
                "","","","","","","","",0,2);
            if ($_GET['cgp']) {

                echo '===============';
                echo $xmlChildOrders;
            }

            $simxml2 = simplexml_load_string($xmlChildOrders);
//            echo $xmlChildOrders;
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }
        else {
//            return $this->format($simxml->Rec);
            return $this->format($simxml->Rec);
        }
    }
    
    public function info($ifpack=1,$concat_id=0){
        // 
        // $buyid = ($_REQUEST['from']=='buy' && $_SESSION['dtype']!=9 && $_SESSION['dtype']!=5 && $_SESSION['dtype']!=2) ? $_SESSION['sid']:'';
        // $saleid = ($_REQUEST['from']=='sale' && $_SESSION['dtype']!=9 && $_SESSION['dtype']!=5 && $_SESSION['dtype']!=2) ? $_SESSION['sid']:'';
        $buyid='';
        $saleid='';
		$xml=$this->s->Order_Globle_Search("",$buyid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,1,"","","","","","","","",$saleid,0,1);
		$simxml = simplexml_load_string($xml);
        //TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info = $this->format($simxml->Rec);
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","", "","","","","","",$this->ordernum,"","","","","",1,1,0,999,"", "","","","","","","","",0,2);
            $simxml2 = simplexml_load_string($xmlChildOrders);
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }else{  // 如果 UUconcat_id 不为 0 表示复票
            if($simxml->Rec->UUconcat_id!=0 && (string)$simxml->Rec->UUconcat_id==(string)$simxml->Rec->UUordernum){
                $xml=$this->s->Order_Globle_Search("",$buyid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,999,"","","","","","","","",$saleid,1,0);
            }
            $simxml = simplexml_load_string($xml);
			$unique = array();
			foreach($simxml->Rec as $row){
				if(isset($unique[(string)$row->UUordernum])) continue;
				$unique[(string)$row->UUordernum] = $row;
			}
			return $this->format($unique);
        }
        return $this->format($simxml->Rec);
	}
	
	// 林俊接口去掉 group by 导致不传 $buyid 返回多条信息
	public function info_n($mid='',$aid=''){
		// 先找主订单
		$xml=$this->s->Order_Globle_Search("",$mid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,1,"","","","","","","","",$aid,0,1);
		$simxml = simplexml_load_string($xml);
		//TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","", "","","","","","",$this->ordernum,"","","","","",1,1,0,15,"", "","","","","","","","",0,2);
            $simxml2 = simplexml_load_string($xmlChildOrders);
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }else{  // 如果 UUconcat_id 不为 0 表示复票
            if($simxml->Rec->UUconcat_id!=0 && (string)$simxml->Rec->UUconcat_id==(string)$simxml->Rec->UUordernum){
                $xml=$this->s->Order_Globle_Search("",$mid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,15,"0","0","","0","","0","","",$aid,1,0);
            }
            $simxml = simplexml_load_string($xml);
        }
        return $this->format($simxml->Rec);
	}
	
	
    /**
     *订单取消函数.
     *联票也一同被返回,故有可存在对个simplexml对象
     *@return bool 成功返回true
     */
    public function cancel($operator, $concat_id=0, $orders=array()){

        // $orders= $concat_id ? $this->info(0, 1):$this->info();
		$orders= count($orders) ? $orders : $this->info_n($operator);
        $array=array();
        $array[] = $orders['mainOrder'];
        /* 9是会员卡下的单 因为有延迟验证无法马上使用 所以又要退掉 zax 2015-06-23 */
        if((int)$orders['mainOrder']->UUordermode==0 || (int)$orders['mainOrder']->UUordermode==9){
			if($operator!=(int)$orders['mainOrder']->UUaid){// 非最下级销售者
				if($operator!=(int)$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权取消");
			}
        }
        else{
            if (isset($_SESSION['mobile']) && !empty($_SESSION['mobile'])) {
                $account = $_SESSION['mobile'];
            } else {
                $str="select account from pft_member where id=$operator limit 1";
                $GLOBALS['le']->query($str);
                $GLOBALS['le']->fetch_assoc();
                $account = $GLOBALS['le']->f("account");
            }

            if( $account !=(int)$orders['mainOrder']->UUcontacttel)
                throw new Exception("非游客自身订单，无权取消{$account}--{$orders['mainOrder']->UUcontacttel}");
        }
        if ($orders['mainOrder']->UUp_type=='F' || $orders['mainOrder']->UUconcat_id==0) {
//			$tuikuan = ((int)$orders['mainOrder']->UUpaystatus==2 || (int)$orders['mainOrder']->UUstatus==2) ? 1:0;
            //2015-07-02  现在所有的订单都退款
            //2015-07-21  未支付不退款
            $tuikuan = 0;
			if((int)$orders['mainOrder']->UUpaystatus==2) $tuikuan =1;// 未支付不退款
            $res = $this->s->Order_Change_Pro((int)$orders['mainOrder']->UUordernum,0,-1,$tuikuan,$operator);
            if($res!=100) return array("code"=>101,"msg"=>$res);
        }
        else {
            $array = array_merge($orders['childOrder'], $array);
            $suc_mark = false;
            foreach($array as $row){
//                 过期和未支付不退款----2015-07-02以前
                //-------------------
                $tuikuan = ((int)$row->UUpaystatus==2) ? 1:0;
                //2015-07-02  现在所有的订单都退款
                //2015-07-21  未支付不退款
//                $tuikuan = 0;
                $res = $this->s->Order_Change_Pro((int)$row->UUordernum,0,-1,$tuikuan,$operator);
                if($res!=100)  $suc_mark = $res;
            }
            if($suc_mark)
                return array("code"=>101,"msg"=>$res);
        }
        /*取消后 重新去读订单的状态 返回给前端的ajax 不刷新页面*/
//        $new_or = $this->info_n();
        return array("code"=>100,"msg"=>$res);
    }

    /**
     * 重发短信函数
     *      update:2015-03-22 11:27:12 by Guangpeng Chen
     * @param null $orders
     * @return mixed
     */
    public function resendMsg($orders=null){

        if (is_null($orders)) {
            $orders = $this->info();
        }

        include '/var/www/html/new/d/class/OrderSmsManual.class.php';
        $smsManual  = new \PFT\SMS\OrderSmsManual($this->s);
        $ret = $smsManual->SendByOrderInfo($orders, false);
        return $ret==100 ? true : $ret;
//        return $this->s->reSend_SMS_Global_PL(
//            (string)$orders['mainOrder']->UUordernum,
//            (string)$orders['mainOrder']->UUaid,
//            (string)$orders['mainOrder']->UUmid);//最后重发短信
    }



    /**
     *修改订单门票数函数.
     *@param int $tid 门票ID
     *@param int $tnum 门票数
     *@param int $operator 操作人ID
     *@return bool 成功返回true
     */
    public function changeTnum($tid,$tnum,$operator, $orders=array()){
        if(empty($orders)){
			$orders = $this->info();
		}
        $array=array();
        $array[]=$orders['mainOrder'];
        if($orders['mainOrder']->UUordermode==0){
            if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权修改数量");
        }else{
            $str="select account from pft_member where id=$operator";
            $GLOBALS['le']->query($str);
            $GLOBALS['le']->fetch_assoc();
            if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUcontacttel)
                throw new Exception("非游客自身订单，无权修改数量");
        }
        $array=array_merge($array,$orders['childOrder']);
        foreach($array as $row){
            if((string)$row->UUtid==$tid&&$tnum<(string)$row->UUtnum){
                $totalprice=(float)$row->UUtprice*$tnum;
                $ret = $this->s->Order_Change_Pro((string)$row->UUordernum,$tnum,$totalprice,0,$operator);
	
                if($ret!=100){
                    // echo $ret;
					
                    return array("code"=>101,"msg"=>$ret);
                }
            }
        }
        return array("code"=>100,"msg"=>$ret);
    }

    /**
     * 修改订单游玩时间函数.
     *
     * @param $begintime 游玩时间
     * @param $operator 操作人ID
     * @param array $orders 订单数据（Guangpeng Chen Add It.）
     * @return bool
     * @throws Exception
     */
    public function changeBegintime($begintime,$operator, $orders=array()){
        if(empty($orders)){
            $orders = $this->info();
        }
        $array[]=$orders['mainOrder'];
        if ($orders['mainOrder']->UUordermode==0 &&
            $operator!=$orders['mainOrder']->UUmid)
        {
            throw new Exception("非自身订单，无权修改时间");
        }
        else {
            // $str="select account from pft_member where id=$operator";
            // $GLOBALS['le']->query($str);
            // $GLOBALS['le']->fetch_assoc();
            // if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
            if($operator!=(string)$orders['mainOrder']->UUbuyid && (string)$orders['mainOrder']->UUremotenum!=0 && ((string)$orders['mainOrder']->UUconcat_id!=0 && (string)$orders['mainOrder']->UUconcat_id!=(string)$orders['mainOrder']->UUordernum))
                throw new Exception("非游客自身订单，无权修改时间");
        }
        $times=strtotime($orders['mainOrder']->UUendtime) - strtotime($orders['mainOrder']->UUbegintime);
//        $times=strtotime($orders['mainOrder']->UUendtime-$UUbegintime);
        $array=array_merge($array,$orders['childOrder']);
        $endtime=date("Y-m-d H:i:s",strtotime($begintime)+$times);
        foreach($array as $row){
            $this->s->Order_Change_Pro((string)$row->UUordernum,-1,-1,1,$operator,$begintime,$endtime);
        }
        return true;
    }

    /**
     *未支付订单支付函数.
     *将处理订单的分润数据，并跳的支付宝支付
     */
    public function alipay(){
        $orderInfo=$this->info();
        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;
        $url="http://www.12301.cc/scenicDetail.html?lid=".$orderInfo['mainOrder']->UUlid;
        
        $mid=(int)$orderInfo['mainOrder']->UUmid;
        $str="select alipay from pft_member where id=$mid LIMIT 1";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $alicount=$GLOBALS['le']->f("alipay");
        $describe="分销商预订".$title;


        $expire_time = "15d";//默认超时时间为15天
        if ($orderInfo['mainOrder']->UUp_type=='H') {
            $sql_expire_time = 'SELECT cancel_auto_onMin FROM uu_jq_ticket WHERE id='.
                (int)$orderInfo['mainOrder']->UUtid.' LIMIT 1';
            $GLOBALS['le']->query($sql_expire_time);
            $GLOBALS['le']->fetch_assoc();
            $expire_time = $GLOBALS['le']->f('cancel_auto_onMin');
            $expire_time = "{$expire_time}m";
        }

        $apply_did=(int)$orderInfo['mainOrder']->UUaid;
//        $str="select alipay,fee_bank from pft_member where id=$apply_did limit 1";
//        $GLOBALS['le']->query($str);
//        $GLOBALS['le']->fetch_assoc();
//        $fee_bank=$GLOBALS['le']->f("fee_bank")/1000;
        
//        $acount1=$GLOBALS['le']->f("alipay");
//        $money1 = $orderInfo['totalPrice']*(1-$fee_bank);
//        $clearDesc1="供应商".$title ."(".$orderid.")分润";
//        $acount2="";
//        $money2="";
//        $clearDesc2="";

        $a_key[]='WIDout_trade_no';
        $a_key[]='WIDsubject';
        $a_key[]='WIDtotal_fee';
        $a_key[]='WIDbody';
        $a_key[]='WIDshow_url';
        $a_key[]='WIDbuyer';
        $a_key[]='buyid';
        $a_key[]='it_b_pay';//过期时间

//        $a_key[]='WIDaccount1';
//        $a_key[]='WIDpay1';
//        $a_key[]='WIDpay1txt';
//        $a_key[]='WIDaccount2';
//        $a_key[]='WIDpay2';
//        $a_key[]='WIDpay2txt';
        
        $a_key[]='return_url';
        $a_key[]='notify_url';
        
        $a_value[]=$orderid;//商户订单号,商户网站订单系统中唯一订单号，必填
        $a_value[]=$title;//订单名称或产品名称，必填
        $a_value[]=$money;//付款金额，必填
        $a_value[]=$describe;//订单描述
        $a_value[]=$url;//产品展示路径 例如：http://www.12301.cc/s_01.html
        $a_value[]=$alicount;//买家绑定的支付宝帐号 最好填上
        $a_value[]=$apply_did;//供应商ID，判断使用哪个支付宝商家账号
        $a_value[]=$expire_time;//订单超时时间

//        $a_value[]=$acount1;//分润帐号1
//        $a_value[]=$money1;//分润1金额 分单位
//        $a_value[]=$clearDesc1;//分润1描述
//        $a_value[]=$acount2;//分润帐号2
//        $a_value[]=$money2;//分润2金额 分单位
//        $a_value[]=$clearDesc2;//分润2描述
        
        $a_value[]="http://www.12301.cc/alipay/ali_order/return_url.php";
        $a_value[]="http://www.12301.cc/alipay/ali_order/notify_url.php";
		// if($_SESSION['sid']==83){
			// $a_value[]="http://www.12301.cc/alipay/ali_order/notify_url_dev.php";
		// }else{
			// $a_value[]="http://www.12301.cc/alipay/ali_order/notify_url.php";
		// }
        /*print_r(array_combine($a_key,$a_value));
        exit;*/
        $this->make_post($a_key,$a_value);
    }


    public function alipayMobile(){
        $orderInfo=$this->info();
        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;

        $a_key[]='WIDout_trade_no';//商户订单号
        $a_key[]='WIDsubject';//订单名称
        $a_key[]='WIDtotal_fee';//付款金额

        $a_value[] = $orderid;//商户订单号,商户网站订单系统中唯一订单号，必填
        $a_value[] = $title;//订单名称或产品名称，必填
        $a_value[] = $money;//付款金额，必填
        $this->make_post($a_key,$a_value, 'http://wx.12301.cc/pay/alipay_v3.3/alipayapi.php');
    }

    /**
     * 未支付订单支付提交函数.
     *  2014年11月25日11:16:44，Updated By Guangpeng Chen.Add Post Url param.
     * @uses OrderRecord::alipay
     * @param $id
     * @param $vid
     * @param null $url
     * @return mixed
     */
    public static function make_post($id, $vid, $url= null){
        $post_data = array();
        if (!is_array($id) && !is_array($vid)){
            $post_data[$id] = $vid;
        }else{
            $post_data = array_combine($id, $vid);
        }
        $url= is_null($url) ? 'http://pay.12301.cc/alipayapi.php' : $url;
//        $o ="";
        $post_data = http_build_query($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
        return curl_exec($ch);
    }

    /**
     * 使用IPS支付
     *
     * @return bool
     */
    public function ipsPay()
    {
        $orderInfo = $this->payCommon();
        $payDate   = date('Ymd');
        $Amount = number_format($orderInfo['money'], 2, '.', '');
        //IPS证书
//        $key = '7667659191929397103470329788807862402627565924638280479623896'.
//          '0393156885586815305050516493889730425518949732797083380078766300585';
        $key = '6868423594683207055317415846359181319229560680572746757844258714459288782574783'.
            '5274502434575961846130383064183151730364216831296';
        $sign      = 'billno'.$orderInfo['orderid'].'currencytypeRMBamount'
            .$Amount.'date'.$payDate.'orderencodetype5'.$key;
        $signMd5   = md5($sign);
        $Bankco = $_POST['Bankco'];
        $payParams = array(
            //'Mer_code'  => '026188',
            'Mer_code'  => '027619',
            'Billno'    => $orderInfo['orderid'],
            'Amount'    => $Amount,
            'Date'      => $payDate,
            'Currency_Type' => 'RMB',
            'Gateway_Type'  => '01',
            'Lang'          => 'GB',
            'Merchanturl'   => 'http://www.12301.cc/ips/ips_return_url.php',
            'FailUrl'   => '',
            'ErrorUrl'  => '',
            'Attach'    => '支付订单'.$orderInfo['orderid'],//商户数据包
            'DispAmount'    => '',
            'OrderEncodeType'   => 5,//订单支付接口加密方式
            'RetEncodeType' => 17,
            'Rettype'   => 1,
            'ServerUrl' => 'http://www.12301.cc/module/zax/ips_pay/ips_notify_url.php',
            'SignMD5'   => $signMd5,
            'DoCredit'  => 1,
            'Bankco'    => $Bankco,
        );

        echo $this->buildPayForm('https://pay.ips.com.cn/ipayment.aspx', $payParams);
        return true;
    }

    /**
     * 构建支付表单
     *
     * @param string $url 提交地址
     * @param array $data  提交的数据
     * @return mixed
     */
    public function buildPayForm($url, Array $data)
    {
        $html = <<<HTML
<html>
  <head>
    <title>跳转......</title>
    <meta http-equiv="content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
   <form action="{$url}" method="post" id="frm1">
   {inputField}
   </form>
   <script language="javascript">
      document.getElementById("frm1").submit();
    </script>
  </body>
</html>
HTML;
        $inputField = '';
        foreach($data as $key=>$val) {
            $inputField .= "<input type='hidden' name='{$key}' value='{$val}'/>";
        }
        return str_replace('{inputField}', $inputField, $html);
    }

    /**
     * 订单数据
     *
     * @return array|bool
     */
    public function payCommon()
    {
        $orderInfo=$this->info();
        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;
        $url="http://www.12301.cc/scenicDetail.html?lid=".$orderInfo['mainOrder']->UUlid;
        $describe="分销商预订".$title;

        goto new_ips;
        //以下是旧的取分润的方式 不用了

        $mid=(string)$orderInfo['mainOrder']->UUmid;
        $str="select alipay from pft_member where id=$mid";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $alicount=$GLOBALS['le']->f("alipay");

        /*****分润1******/
        $apply_did=(string)$orderInfo['mainOrder']->UUaid;
        $str="select alipay,fee_bank from pft_member where id=$apply_did";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $fee_bank=$GLOBALS['le']->f("fee_bank")/1000;
//            $acount1=$GLOBALS['le']->f("alipay");
        $money1 = $orderInfo['totalPrice']*(1-$fee_bank);//对应$apply_did

        $clearDesc1 = "供应商".$title ."(".$orderid.")分润";
        $money2     = 0;
        $clearDesc2 = "";
        if($orderInfo['mainOrder']->UUordermode==1
            &&(int)$orderInfo['mainOrder']->UUmid!=(int)$orderInfo['mainOrder']->UUaid){//普通用户下单

            $money2=0; //对应(int)$orderInfo['mainOrder']->UUmid
            $clearDesc2="分销商" . $title ."(".$orderid.")分润";
            /*分销商利润*/
            $orders=array(0=>$orderInfo['mainOrder']);
            $orders=array_merge($orders, $orderInfo['childOrder']);
            foreach ($orders as $row){
                $mid = (int)$row->UUmid;
                $pid = (int)$row->UUpid;
                $pro = new ProductInfo($this->s, $pid);
                //分销权限判定
                if(!$pro->supply($mid)) return false;
                if((float)$row->UUaprice==0) return false;
                $dprice = $pro->dprice($mid);
                $money2 += ($row->UUtprice - $row->UUaprice - $dprice) * (int)$row->UUtnum;
            }
            /*供应商利润*/
            $money1     = ($money1-$money2);
        }
        //供应商分润
        $royalty_parameters = "$apply_did^$money1^$clearDesc1";
        //散客购买，分销商分润
        if($money2>0) {
            $mid2 = (int)$orderInfo['mainOrder']->UUmid;
            $royalty_parameters .= "|$mid2^$money2^$clearDesc2";
        }
        new_ips:
        //支付记录,先判断是否存在记录
//        $sql_chk = "SELECT id FROM pft_ips_rec WHERE out_trade_no='{$orderid}'";
        $sql_chk="select id from pft_alipay_rec where out_trade_no='$orderid' /*AND sourceT=2*/ LIMIT 1";
        $GLOBALS['le']->query($sql_chk);
        $res = $GLOBALS['le']->fetch_assoc();
        $merID = '027619';
        $total_fee = $orderInfo['totalPrice']/100;
        if(!$res['id']) {
            //todo 原来是往ips_rec表里记录数据
//            $sql_log_ips = "INSERT INTO pft_ips_rec(fid,royalty_parameters,".
//                " total_fee, out_trade_no,subject) VALUES($mid,'$royalty_parameters',".
//                "{$orderInfo['totalPrice']},'$orderid','$describe')";
//            $GLOBALS['le']->query($sql_log_ips);

                $str=<<<SQL
INSERT INTO pft_alipay_rec SET out_trade_no='$orderid',
seller_email='$merID',buyer_email='',
subject='$describe',total_fee='$total_fee',description='',
show_url='$url',sourceT=3/*3代表环迅*/
SQL;
            }
            else {
                $str=<<<SQL
update pft_alipay_rec set seller_email='$merID',
buyer_email='',subject='$describe',total_fee='$total_fee',
description='',show_url='$url',
royalty_parameters='',sourceT=3
where out_trade_no='$orderid' LIMIT 1
SQL;
            }
        $GLOBALS['le']->query($str);
        @$GLOBALS['le']->close();


        return compact('orderid', 'title', 'money', 'describe', 'url',
            'alicount', 'acount1', 'money1', 'clearDesc1', 'acount2',
            'money2', 'clearDesc2');
    }
}
?>